package wang.hu.bos.service.Impl;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import wang.hu.bos.dao.AreaDao;
import wang.hu.bos.dao.FixedAreaDao;
import wang.hu.bos.dao.OrderDao;
import wang.hu.bos.dao.WorkBillDao;
import wang.hu.bos.domain.base.Area;
import wang.hu.bos.domain.base.Courier;
import wang.hu.bos.domain.base.FixedArea;
import wang.hu.bos.domain.base.SubArea;
import wang.hu.bos.domain.take_delivery.Order;
import wang.hu.bos.domain.take_delivery.WorkBill;
import wang.hu.bos.service.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private FixedAreaDao fixedAreaDao;
	@Autowired
	private AreaDao areaDao;
	@Resource(name = "jmsQueueTemplate")
	private JmsTemplate jmsQueueTemplate;
	@Autowired
	private WorkBillDao workBillDao;

	@Override
	public void saveOrder(Order order) {
		Area recArea = order.getRecArea();
		Area persistentRecArea = areaDao
				.findByProvinceAndCityAndDistrict(recArea.getProvince(),
						recArea.getCity(), recArea.getDistrict());
		Area sendArea = order.getSendArea();
		Area persistentArea = areaDao.findByProvinceAndCityAndDistrict(
				sendArea.getProvince(), sendArea.getCity(),
				sendArea.getDistrict());
		order.setSendArea(persistentArea);
		order.setRecArea(persistentRecArea);
		String sendAddress = order.getSendAddress();

		// 通过详细地址查找客户并找到客户所关联的定区从而找到快递员完成自动分单
		String fixedAreaId = WebClient
				.create("http://localhost:9111/crm_management/services/customerService/findfixedareaId/"
						+ order.getSendAddress())
				.accept(MediaType.APPLICATION_JSON).get(String.class);
		if (fixedAreaId != null) {
			FixedArea fixedArea = fixedAreaDao.findOne(fixedAreaId);
			Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
			if (iterator.hasNext()) {
				Courier courier = iterator.next();
				order.setCourier(courier);
				order.setOrderType("1"); // 分单类型 1 自动分单 2 人工分单
				order.setStatus("1"); // 订单状态 1 待取件 2 运输中 3 已签收 4 异常
				orderDao.save(order);
				System.out.println("通过详细地址匹配客户定区来自动分单成功!");
				// 发送短信
				creatWorkBill(order);
				return;
			}
			System.out.println("当前定区:" + fixedArea.getFixedAreaName()
					+ "未关联快递员,正在尝试通过查找分区完成分单.....");
		}
		// 通过详细地址中的关键字与当前区域所关联的分区所记录的关键字进行匹配从而确定分区,然后通过分区找到关联定区完成分单
		Set<SubArea> subareas = persistentArea.getSubareas();
		if (subareas != null && subareas.size() > 0) {
			Iterator<SubArea> iterator = subareas.iterator();
			while (iterator.hasNext()) {
				SubArea subArea = iterator.next();
				if (sendAddress.contains(subArea.getKeyWords())
						|| sendAddress.contains(subArea.getAssistKeyWords())) {
					FixedArea fixedArea = subArea.getFixedArea();
					Iterator<Courier> iterator2 = fixedArea.getCouriers()
							.iterator();
					if (iterator2.hasNext()) {
						Courier courier = iterator2.next();
						order.setCourier(courier);
						order.setOrderType("1"); // 分单类型 1 自动分单 2 人工分单
						order.setStatus("1"); // 订单状态 1 待取件 2 运输中 3 已签收 4 异常
						orderDao.save(order);
						System.out
								.println("通过详细地址中的关键字与当前区域所关联的分区所记录的关键字进行匹配来自动分单成功!");
						// 发送短信
						creatWorkBill(order);
						return;
					}
					System.out.println("定区:" + fixedArea.getFixedAreaName()
							+ "未关联快递员,正在尝试通过查找下一个分区完成分单.....");
				}
			}
		}

		// 自动分单失败
		order.setOrderType("2");
		order.setStatus("1");
		orderDao.save(order);
		System.out.println("自动分单失败,已完成手动分单!");
	}

	private void creatWorkBill(final Order order) {
		String msgNumber = RandomStringUtils.randomNumeric(4);
		WorkBill workBill = new WorkBill();
		workBill.setBuildtime(new Date());
		workBill.setCourier(order.getCourier());
		workBill.setOrder(order);
		workBill.setRemark(order.getRecMobile());
		workBill.setSmsNumber(msgNumber);
		workBill.setType("新");
		workBill.setPickstate("新单");
		workBillDao.save(workBill);
		// 发送短信
		final String content = "短信序号:" + msgNumber + ",取件地址:"
				+ order.getSendAddress() + "。联系电话:" + order.getSendMobile()
				+ "客户备注:" + order.getSendMobileMsg();
		jmsQueueTemplate.send("bos_msg", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier()
						.getTelephone());
				mapMessage.setString("content", content);
				return mapMessage;
			}
		});
		workBill.setPickstate("已通知");
		System.out.println("已通知到快递员:" + workBill.getCourier().getName()
				+ "前往取件!");
	}

	@Override
	public Order findByOrderNum(String orderNum) {
		return orderDao.findByOrderNum(orderNum);
	}
}
